package com.sunrise.configuracoes.repositorio;

import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.sunrise.configuracoes.repositorio.iface.SerieNFDao;
import com.sunrise.generico.acesso.DaoService;
import com.sunrise.generico.entidade.SerieNF;
import com.sunrise.generico.visao.Filtro;

@Repository
public class SerieNFDaoImpl extends DaoService<SerieNF> implements SerieNFDao {

	public List<SerieNF> listarOrdenado() {
		List<SerieNF> list = listar(SerieNF.class);
		Collections.sort(list, new Comparator<SerieNF>() {

			@Override
			public int compare(SerieNF o1, SerieNF o2) {
				return o1.getNome().compareTo(o2.getNome());
			}
		});
		return list;
	}

	public List<SerieNF> search(SerieNF ex) {
		List<SerieNF> list =  searchByExample(SerieNF.class, ex);
		Collections.sort(list, new Comparator<SerieNF>() {

			@Override
			public int compare(SerieNF o1, SerieNF o2) {
				return o1.getNome().compareTo(o2.getNome());
			}
		});
		return list;
	}

	public SerieNF getById(Long id) {
		return getById(id, SerieNF.class);
	}
	
	
	@SuppressWarnings("unchecked")
	@Override
	public List<SerieNF> listarPorNome(String nome) {
		Criteria crit = getSession().createCriteria(SerieNF.class);
		crit.add(Restrictions.ilike("nome", nome, MatchMode.ANYWHERE));
		return crit.list();
	}
	
	
	@SuppressWarnings("unchecked")
	@Override
	public Collection<SerieNF> buscarPorFiltros(Filtro serieNF) {
		Criteria crit = getSession().createCriteria(SerieNF.class);
		if(serieNF.getNumero() != null && !serieNF.getNumero().equals(0)){
			crit.add(Restrictions.eq("codigo", serieNF.getNumero()));
		}
		
		if (serieNF.getNome() != null && !serieNF.getNome().isEmpty()) {
			crit.add(Restrictions.ilike("nome", serieNF.getNome(),
					MatchMode.ANYWHERE));
		}

		if (serieNF.getAtivo() != null) {
			crit.add(Restrictions.eq("ativo", serieNF.getAtivo().getCodigo()));
		}
		
		crit.addOrder(Order.asc("nome"));
		return crit.list();
	}

	@Override
	public SerieNF buscarPorCodigo(String codigo) {
		Criteria crit = getSession().createCriteria(SerieNF.class);
		crit.add(Restrictions.eq("codigo", codigo));
		return (SerieNF) crit.uniqueResult();
	}
	
	@Override
	public SerieNF buscarPorNome(String nome) {
		Criteria crit = getSession().createCriteria(SerieNF.class);
		crit.add(Restrictions.eq("nome", nome).ignoreCase());
		return (SerieNF) crit.uniqueResult();
	}

}
